//+------------------------------------------------------------------+
//|                        暴富黄金超能黄金天子黄金_Complete_MQ5.mq5     |
//|                    重构优化版 - 保持核心逻辑不变                   |
//|                                                                  |
//| 【BTC适配说明】：                                                |
//| • BTC：1手=1个BTC（与黄金1手=100盎司不同）                       |
//| • BTC点差参数约2160左右（实盘上限2400，回测上限2200）             |
//| • BTC手数限制：最小0.01手，最大5手（黄金最大50手）                |
//| • BTC复利计算：使用10万作为除数（黄金用100万）                    |
//| • 支持品种：包含"BTC"或"BITCOIN"的交易品种                       |
//+------------------------------------------------------------------+
#property copyright "重构优化版EA - 保持核心逻辑不变"
#property version   "2.00"

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>

//+------------------------------------------------------------------+
//| 外部参数设置                                                     |
//+------------------------------------------------------------------+
input string eaComment = "王者无敌";                    // EA注释
input bool enableDynamicLots = false;                  // 动态手数开关 (原DongTaiKaiGuan)
input int volatilityPeriod = 59;                       // 波动率周期 (原BoDongLu)
input int adaptivePeriod = 68;                         // 自适应周期 (原ZiShiYing)
input int openFactor = 10;                             // 开仓因子 (原KaiCangYinZi)
input int closeFactor = 15;                            // 平仓因子 (原PingCangYinZi)
input int closeFactor2 = 31;                           // 平仓因子2 (原PingCangYinZi2)
input int speedPeriod = 9;                             // 速度周期 (原SuDuYinZi)
input int profitFactor = 15;                           // 盈利因子 (原YingLiYinZi)
input double baseLotSize = 0.1;                        // 基础手数 (原Lots)
input bool enableCompounding = false;                  // 复利开关 (原FuliKaiGuan)
input int riskPercent = 10;                            // 风险百分比 (原Risk)
input string separator1 = "========== 亚盘策略 =========="; // 分隔符
input bool enableAsianSession = false;                 // 亚盘策略开关 (原ZaoPan)
input int asianStartHour = 1;                          // 亚盘开始时间 (原Tima)
input int asianEndHour = 19;                           // 亚盘结束时间 (原Timb)
input int stopLossPoints = 114;                        // 止损点数 (原StopLos)

//+------------------------------------------------------------------+
//| ChaoNeng 交易策略类 - 面向对象重构                               |
//+------------------------------------------------------------------+
class CChaoNengStrategy
{
private:
    // 核心交易对象
    CTrade m_trade;
    CPositionInfo m_position;
    
    // 常量设置
    static const int MAGIC_NUMBER;
    static const int SLIPPAGE_POINTS;
    static const datetime EXPIRY_DATE;
    
    // 交易控制变量
    bool m_tradingAllowed;
    bool m_spreadOK;
    int m_pipsFactor;                                   // 点值因子 (原by_in_11)
    double m_pointSize;                                 // 点大小 (原by_do_14)
    int m_freezeLevel;                                  // 冻结级别 (原by_in_17)
    
    // 价格数据
    double m_askPrice;                                  // 卖价 (原by_do_18)
    double m_bidPrice;                                  // 买价 (原by_do_19)  
    double m_currentSpread;                             // 当前点差 (原by_do_20)
    
    // 技术指标数据 - 缓存机制
    datetime m_lastBarTime;                             // 上次K线时间
    double m_adaptiveHigh;                              // 自适应高点
    double m_adaptiveLow;                               // 自适应低点
    double m_speedHigh;                                 // 速度高点
    double m_speedLow;                                  // 速度低点
    double m_chaoNengValue;                             // 超能指标值
    
    // 持仓统计数据
    int m_longPositions;                                // 多单数量 (原by_in_21)
    int m_shortPositions;                               // 空单数量 (原by_in_22)
    double m_longLots;                                  // 多单手数 (原by_do_23)
    double m_shortLots;                                 // 空单手数 (原by_do_24)
    double m_longProfit;                                // 多单盈亏 (原by_do_27)
    double m_shortProfit;                               // 空单盈亏 (原by_do_28)
    double m_longOpenPrice;                             // 多单开仓价 (原by_do_32)
    double m_shortOpenPrice;                            // 空单开仓价 (原by_do_33)
    datetime m_longOpenTime;                            // 多单开仓时间 (原by_lo_41)
    datetime m_shortOpenTime;                           // 空单开仓时间 (原by_lo_42)
    
    // 信号控制
    datetime m_lastLongSignal;                          // 上次多单信号时间 (原by_lo_37/38)
    datetime m_lastShortSignal;                         // 上次空单信号时间 (原by_lo_39/40)
    long m_barTimeInterval;                             // K线时间间隔 (原by_lo_43)
    
public:
    // 构造函数
    CChaoNengStrategy();
    
    // 主要接口
    bool Initialize();
    void OnNewTick();
    void OnDeinitialize();
    void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam);
    
private:
    // 核心逻辑方法
    void UpdateTechnicalIndicators();
    void CheckTradingPermissions();
    void CheckSpreadConditions();
    void ProcessMainTradingLogic();
    void ProcessAsianSessionLogic();
    void ProcessClosingLogic();
    void UpdatePositionStatistics();
    
    // 交易执行
    void ExecuteLongEntry();
    void ExecuteShortEntry();
    void ClosePositions(ENUM_POSITION_TYPE posType);
    
    // ChaoNeng 算法函数 (保持原始逻辑)
    double CalculateChaoNengIndicator(double high, double close, double highest, double lowest);
    bool ChaoNeng_LongEntry(double closePrice, double adaptiveLow, double chaoNengVal, double speedLow);
    bool ChaoNeng_ShortEntry(double adaptiveHigh, double closePrice, double chaoNengVal, double speedHigh);
    bool ChaoNeng_SpecialLongEntry(double currentPrice, double adaptiveHigh, double adaptiveLow);
    bool ChaoNeng_SpecialShortEntry(double currentPrice, double adaptiveHigh, double adaptiveLow);
    // 亚洲时段专用函数
    bool ChaoNeng_LongEntry_Asian(double closePrice, double adaptiveLow, double chaoNengVal, double speedLow);
    bool ChaoNeng_ShortEntry_Asian(double adaptiveHigh, double closePrice, double chaoNengVal, double speedHigh);
    bool ChaoNeng_SpecialLongEntry_Asian(double currentPrice, double adaptiveHigh, double adaptiveLow);
    bool ChaoNeng_SpecialShortEntry_Asian(double currentPrice, double adaptiveHigh, double adaptiveLow);
    // 平仓函数
    bool ChaoNeng_LongBreakoutClose(double closePrice, double speedHigh, double chaoNengVal);
    bool ChaoNeng_ShortBreakoutClose(double closePrice, double speedLow, double chaoNengVal);
    bool ChaoNeng_LongProfitClose(double closePrice);
    bool ChaoNeng_ShortProfitClose(double closePrice);
    bool ChaoNeng_LongPnLClose(double chaoNengVal);
    bool ChaoNeng_ShortPnLClose(double chaoNengVal);
    
    // 辅助方法
    double GetHighestPrice(int period, int shift);
    double GetLowestPrice(int period, int shift);
    double CalculateLotSize();
    void SetTimeInterval();
    bool IsAsianSession();
    void UpdateDisplay();
    void CreateUIElements();
    void CreateLabel(string name, string text, int corner, int x, int y, int size, color clr);
};

// 静态常量定义
const int CChaoNengStrategy::MAGIC_NUMBER = 19828668;
const int CChaoNengStrategy::SLIPPAGE_POINTS = 3;
const datetime CChaoNengStrategy::EXPIRY_DATE = D'2027.03.02';

// 全局策略实例
CChaoNengStrategy g_strategy;

//+------------------------------------------------------------------+
//| 构造函数                                                         |
//+------------------------------------------------------------------+
CChaoNengStrategy::CChaoNengStrategy()
{
    // 初始化交易控制变量
    m_tradingAllowed = true;
    m_spreadOK = true;
    m_pipsFactor = 10;
    m_pointSize = 0.0;
    m_freezeLevel = 0;
    
    // 初始化价格数据
    m_askPrice = 0.0;
    m_bidPrice = 0.0;
    m_currentSpread = 0.0;
    
    // 初始化技术指标数据
    m_lastBarTime = 0;
    m_adaptiveHigh = 0.0;
    m_adaptiveLow = 0.0;
    m_speedHigh = 0.0;
    m_speedLow = 0.0;
    m_chaoNengValue = 0.0;
    
    // 初始化持仓统计
    m_longPositions = 0;
    m_shortPositions = 0;
    m_longLots = 0.0;
    m_shortLots = 0.0;
    m_longProfit = 0.0;
    m_shortProfit = 0.0;
    m_longOpenPrice = 0.0;
    m_shortOpenPrice = 0.0;
    m_longOpenTime = 0;
    m_shortOpenTime = 0;
    
    // 初始化信号控制
    m_lastLongSignal = 0;
    m_lastShortSignal = 0;
    m_barTimeInterval = 0;
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    return g_strategy.Initialize() ? INIT_SUCCEEDED : INIT_FAILED;
}

//+------------------------------------------------------------------+
//| 策略初始化                                                       |
//+------------------------------------------------------------------+
bool CChaoNengStrategy::Initialize()
{
    // 设置上次K线时间
    m_lastBarTime = iTime(_Symbol, _Period, 1);
    
    // 计算点值大小
    m_pointSize = MathPow(0.1, _Digits);
    
    // 根据小数位数设置点值因子
    if(_Digits == 5 || _Digits == 3) 
        m_pipsFactor = 10;
    
    // 黄金特殊处理
    if(StringFind(_Symbol, "XAU", 0) >= 0 || StringFind(_Symbol, "GOLD", 0) >= 0)
    {
        if(_Digits == 2) m_pipsFactor = 10;
        if(_Digits == 3) m_pipsFactor = 100;
        if(_Digits == 4) m_pipsFactor = 1000;
        Print("【黄金适配】品种:", _Symbol, " 小数位数:", _Digits, " 点值因子:", m_pipsFactor);
    }
    
    // BTC特殊处理 - 1手=1个BTC，与黄金1手=100盎司不同
    if(StringFind(_Symbol, "BTC", 0) >= 0 || StringFind(_Symbol, "BITCOIN", 0) >= 0)
    {
        if(_Digits == 0) m_pipsFactor = 1;      // 整数价格
        if(_Digits == 1) m_pipsFactor = 10;     // 一位小数
        if(_Digits == 2) m_pipsFactor = 100;    // 两位小数（常见）
        if(_Digits == 3) m_pipsFactor = 1000;   // 三位小数
        
        Print("【BTC适配】品种:", _Symbol, " 小数位数:", _Digits, " 点值因子:", m_pipsFactor, " 当前价格:", SymbolInfoDouble(_Symbol, SYMBOL_ASK));
    }
    
    // 通用品种信息
    Print("【初始化】品种:", _Symbol, " 周期:", EnumToString((ENUM_TIMEFRAMES)_Period), " 点值因子:", m_pipsFactor, " 点大小:", m_pointSize);
    
    // 获取冻结级别
    m_freezeLevel = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
    
    // 显示交易水平线
    ChartSetInteger(0, CHART_SHOW_TRADE_LEVELS, true);
    
    // 创建UI元素
    CreateUIElements();
    
    // 设置交易参数
    m_trade.SetExpertMagicNumber(MAGIC_NUMBER);
    m_trade.SetDeviationInPoints(SLIPPAGE_POINTS * m_pipsFactor);
    
    return true;
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    g_strategy.OnNewTick();
}

//+------------------------------------------------------------------+
//| 主要Tick处理逻辑                                                 |
//+------------------------------------------------------------------+
void CChaoNengStrategy::OnNewTick()
{
    // M5时间框架不交易
    if(_Period == PERIOD_M5) return;
    
    // 更新当前价格和点差
    m_askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    m_bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    m_currentSpread = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point;
    
    // 重置交易权限标志
    m_tradingAllowed = true;
    
    // 检查交易条件
    CheckTradingPermissions();
    CheckSpreadConditions();
    
    // 更新持仓统计
    UpdatePositionStatistics();
    
    // 检查是否为新K线 - 技术指标缓存机制
    datetime currentBarTime = iTime(_Symbol, _Period, 1);
    if(m_lastBarTime != currentBarTime)
    {
        // 只在新K线时更新技术指标，提高效率
        Print("【新K线】", EnumToString((ENUM_TIMEFRAMES)_Period), " 时间:", TimeToString(currentBarTime), " 价格:", m_askPrice, " 点差:", DoubleToString(m_currentSpread/_Point, 2));
        UpdateTechnicalIndicators();
        
        
        m_lastBarTime = currentBarTime;
    }
    // 处理平仓逻辑
    ProcessClosingLogic();
    
    // 设置时间间隔
    SetTimeInterval();
    
    // 处理开仓逻辑
    ProcessMainTradingLogic();
    ProcessAsianSessionLogic();
    
    // 更新显示
    UpdateDisplay();
    
    // GBPCAD特殊提醒
    if(enableAsianSession == false && StringFind(_Symbol, "GBPCAD", 0) >= 0)
    {
        Alert("请把亚盘开关打开");
        Sleep(100000);
    }
}

//+------------------------------------------------------------------+
//| 更新技术指标 - 缓存机制，只在新K线时计算                          |
//+------------------------------------------------------------------+
void CChaoNengStrategy::UpdateTechnicalIndicators()
{
    // 计算自适应周期的高低点
    m_adaptiveHigh = GetHighestPrice(adaptivePeriod, 2);
    m_adaptiveLow = GetLowestPrice(adaptivePeriod, 2);
    
    // 计算速度周期的高低点
    m_speedHigh = GetHighestPrice(speedPeriod, 2);
    m_speedLow = GetLowestPrice(speedPeriod, 2);
    
    // 计算超能指标
    double currentClose = iClose(_Symbol, _Period, 1);
    double speedHighCurrent = GetHighestPrice(speedPeriod, 1);
    double speedLowCurrent = GetLowestPrice(speedPeriod, 1);
    
    m_chaoNengValue = 0;
    if(speedHighCurrent - currentClose > 0)
    {
        m_chaoNengValue = CalculateChaoNengIndicator(speedHighCurrent, currentClose, speedHighCurrent, speedLowCurrent);
    }
    
    // 打印技术指标更新日志
    Print("【技术指标更新】自适应高:", m_adaptiveHigh, " 低:", m_adaptiveLow, " 速度高:", m_speedHigh, " 低:", m_speedLow, " 超能值:", m_chaoNengValue);
    
    // 超能指标限制检查
    if(m_chaoNengValue == 100)
    {
        m_tradingAllowed = false;
        Print("【交易限制】超能指标达到100，暂停交易");
    }
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    g_strategy.OnDeinitialize();
}

//+------------------------------------------------------------------+
//| 策略反初始化                                                     |
//+------------------------------------------------------------------+
void CChaoNengStrategy::OnDeinitialize()
{
    ObjectsDeleteAll(0, 0, OBJ_LABEL);
    ObjectDelete(0, "EURUSD");
}

//+------------------------------------------------------------------+
//| 检查交易权限                                                     |
//+------------------------------------------------------------------+
void CChaoNengStrategy::CheckTradingPermissions()
{
    if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
    {
        CreateLabel("启动", "请点击上方-自动交易-按钮", 100, 100, 80, 9, clrChocolate);
        m_tradingAllowed = false;
    }
    else
    {
        CreateLabel("启动", "", 100, 100, 80, 10, clrChocolate);
    }
    
    if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
    {
        CreateLabel("启动", "请把允许实时自动交易打勾", 100, 100, 80, 9, clrChocolate);
        m_tradingAllowed = false;
    }
}

//+------------------------------------------------------------------+
//| 检查点差条件                                                     |
//+------------------------------------------------------------------+
void CChaoNengStrategy::CheckSpreadConditions()
{
    if(MQLInfoInteger(MQL_TESTER))
    {
        // 回测点差检查
        if((StringFind(_Symbol, "GBPUSD", 0) >= 0 && m_currentSpread > m_pipsFactor * 2.5 * _Point) ||
           (StringFind(_Symbol, "XAUUSD", 0) >= 0 && m_currentSpread > m_pipsFactor * 3.5 * _Point) ||
           (StringFind(_Symbol, "GOLD", 0) >= 0 && m_currentSpread > m_pipsFactor * 3.5 * _Point) ||
           (StringFind(_Symbol, "USDJPY", 0) >= 0 && m_currentSpread > m_pipsFactor * 2 * _Point) ||
           (StringFind(_Symbol, "GBPCAD", 0) >= 0 && m_currentSpread > m_pipsFactor * 4 * _Point) ||
           (StringFind(_Symbol, "BTC", 0) >= 0 && m_currentSpread > m_pipsFactor * 2200 * _Point) ||   // BTC回测点差上限
           (StringFind(_Symbol, "BITCOIN", 0) >= 0 && m_currentSpread > m_pipsFactor * 2200 * _Point))
        {
            CreateLabel("回测", "您回测点差过大，请照ECN平台点差设置", 100, 100, 200, 9, clrChocolate);
            m_tradingAllowed = false;
        }
    }
    else
    {
        // 实盘点差检查
        if((StringFind(_Symbol, "GBPUSD", 0) >= 0 && m_currentSpread > m_pipsFactor * 2.6 * _Point) ||
           (StringFind(_Symbol, "XAUUSD", 0) >= 0 && m_currentSpread > m_pipsFactor * 3.7 * _Point) ||
           (StringFind(_Symbol, "GOLD", 0) >= 0 && m_currentSpread > m_pipsFactor * 3.7 * _Point) ||
           (StringFind(_Symbol, "USDJPY", 0) >= 0 && m_currentSpread > m_pipsFactor * 2.3 * _Point) ||
           (StringFind(_Symbol, "GBPCAD", 0) >= 0 && m_currentSpread > m_pipsFactor * 5 * _Point) ||
           (StringFind(_Symbol, "BTC", 0) >= 0 && m_currentSpread > m_pipsFactor * 2400 * _Point) ||   // BTC实盘点差上限
           (StringFind(_Symbol, "BITCOIN", 0) >= 0 && m_currentSpread > m_pipsFactor * 2400 * _Point))
        {
            CreateLabel("点差", "点差过高 : ", CORNER_LEFT_UPPER, 10, 30, 10, clrRed);
            CreateLabel("点差2", DoubleToString(m_currentSpread/_Point, 2), CORNER_LEFT_UPPER, 85, 30, 10, clrRed);
            m_spreadOK = false;
            Print(TimeToString(TimeCurrent(), TIME_MINUTES) + " ,点差过高! 当前点差: " + DoubleToString(m_currentSpread/_Point, 2));
        }
        else
        {
            CreateLabel("点差", "点    差 : ", CORNER_LEFT_UPPER, 10, 30, 10, clrDodgerBlue);
            CreateLabel("点差2", DoubleToString(m_currentSpread/_Point, 2), CORNER_LEFT_UPPER, 85, 30, 10, clrDodgerBlue);
            m_spreadOK = true;
            // Print("【点差检查】点差正常: ", DoubleToString(m_currentSpread/_Point, 2), " 品种:", _Symbol);
        }
    }
}



//+------------------------------------------------------------------+
//| 处理主要交易逻辑                                                 |
//+------------------------------------------------------------------+
void CChaoNengStrategy::ProcessMainTradingLogic()
{
    // 非GBPCAD货币对的正常交易逻辑
    if(StringFind(_Symbol, "GBPCAD", 0) != 0)
    {
        double currentClose = iClose(_Symbol, _Period, 1);
        datetime currentBarTime = iTime(_Symbol, _Period, 1);
        
        // 普通多单开仓条件
        if(ChaoNeng_LongEntry(currentClose, m_adaptiveLow, m_chaoNengValue, m_speedLow) &&
           m_lastLongSignal != currentBarTime && 
           m_tradingAllowed == true && 
           m_askPrice < m_pipsFactor * 5 * m_pointSize + currentClose)
        {
            m_lastLongSignal = currentBarTime;
            ExecuteLongEntry();
        }
        
        // 普通空单开仓条件
        if(ChaoNeng_ShortEntry(m_adaptiveHigh, currentClose, m_chaoNengValue, m_speedHigh) &&
           m_lastShortSignal != currentBarTime && 
           m_tradingAllowed == true && 
           m_askPrice > currentClose - m_pipsFactor * 5 * m_pointSize)
        {
            m_lastShortSignal = currentBarTime;
            ExecuteShortEntry();
        }
        
        // 特殊多单开仓条件（持仓限制5个以内）
        if(ChaoNeng_SpecialLongEntry(m_bidPrice, m_adaptiveHigh, m_adaptiveLow) &&
           m_lastLongSignal != currentBarTime && 
           (int)TimeCurrent() - (int)currentBarTime <= m_barTimeInterval && 
           m_tradingAllowed == true && 
           m_askPrice < m_pipsFactor * 5 * m_pointSize + currentClose)
        {
            m_lastLongSignal = currentBarTime;
            ExecuteLongEntry();
        }
        
        // 特殊空单开仓条件（持仓限制5个以内）
        if(ChaoNeng_SpecialShortEntry(m_askPrice, m_adaptiveHigh, m_adaptiveLow) &&
           m_lastShortSignal != currentBarTime && 
           (int)TimeCurrent() - (int)currentBarTime <= m_barTimeInterval && 
           m_tradingAllowed == true && 
           m_askPrice > currentClose - m_pipsFactor * 5 * m_pointSize)
        {
            m_lastShortSignal = currentBarTime;
            ExecuteShortEntry();
        }
    }
}

//+------------------------------------------------------------------+
//| 处理亚洲时段交易逻辑 - GBPCAD特殊策略                              |
//+------------------------------------------------------------------+
void CChaoNengStrategy::ProcessAsianSessionLogic()
{
    if(enableAsianSession == true && StringFind(_Symbol, "GBPCAD", 0) >= 0 && IsAsianSession())
    {
        double currentClose = iClose(_Symbol, _Period, 1);
        datetime currentBarTime = iTime(_Symbol, _Period, 1);
        
        // GBPCAD亚洲时段特殊交易条件 - 波动性要求
        bool lowVolatility = (m_speedHigh - m_speedLow < m_pipsFactor * 180 * m_pointSize);
        
        // GBPCAD早盘多单开仓 - 特殊参数设置
        if(ChaoNeng_LongEntry_Asian(currentClose, m_adaptiveLow, m_chaoNengValue, m_speedLow) &&
           m_lastLongSignal != currentBarTime && 
           m_tradingAllowed == true && 
           lowVolatility &&
           m_askPrice < m_pipsFactor * 5 * m_pointSize + currentClose)
        {
            m_lastLongSignal = currentBarTime;
            ExecuteLongEntry();
        }
        
        // GBPCAD早盘空单开仓 - 特殊参数设置
        if(ChaoNeng_ShortEntry_Asian(m_adaptiveHigh, currentClose, m_chaoNengValue, m_speedHigh) &&
           m_lastShortSignal != currentBarTime && 
           m_tradingAllowed == true && 
           lowVolatility &&
           m_askPrice > currentClose - m_pipsFactor * 5 * m_pointSize)
        {
            m_lastShortSignal = currentBarTime;
            ExecuteShortEntry();
        }
        
        // 特殊亚洲时段条件
        if(ChaoNeng_SpecialLongEntry_Asian(m_bidPrice, m_adaptiveHigh, m_adaptiveLow) &&
           m_lastLongSignal != currentBarTime && 
           (int)TimeCurrent() - (int)currentBarTime <= m_barTimeInterval && 
           m_tradingAllowed == true && 
           m_askPrice < m_pipsFactor * 5 * m_pointSize + currentClose)
        {
            m_lastLongSignal = currentBarTime;
            ExecuteLongEntry();
        }
        
        if(ChaoNeng_SpecialShortEntry_Asian(m_askPrice, m_adaptiveHigh, m_adaptiveLow) &&
           m_lastShortSignal != currentBarTime && 
           (int)TimeCurrent() - (int)currentBarTime <= m_barTimeInterval && 
           m_tradingAllowed == true && 
           m_askPrice > currentClose - m_pipsFactor * 5 * m_pointSize)
        {
            m_lastShortSignal = currentBarTime;
            ExecuteShortEntry();
        }
    }
}

//+------------------------------------------------------------------+
//| 处理平仓逻辑                                                     |
//+------------------------------------------------------------------+
void CChaoNengStrategy::ProcessClosingLogic()
{
    double currentClose = iClose(_Symbol, _Period, 1);
    
    // 多单突破平仓
    if(ChaoNeng_LongBreakoutClose(currentClose, m_speedHigh, m_chaoNengValue))
    {
        ClosePositions(POSITION_TYPE_BUY);
    }
    
    // 空单突破平仓
    if(ChaoNeng_ShortBreakoutClose(currentClose, m_speedLow, m_chaoNengValue))
    {
        ClosePositions(POSITION_TYPE_SELL);
    }
    
    // 多单盈利平仓
    if(ChaoNeng_LongProfitClose(currentClose))
    {
        ClosePositions(POSITION_TYPE_BUY);
    }
    
    // 空单盈利平仓
    if(ChaoNeng_ShortProfitClose(currentClose))
    {
        ClosePositions(POSITION_TYPE_SELL);
    }
    
    // 多单盈亏平仓
    if(ChaoNeng_LongPnLClose(m_chaoNengValue))
    {
        ClosePositions(POSITION_TYPE_BUY);
    }
    
    // 空单盈亏平仓
    if(ChaoNeng_ShortPnLClose(m_chaoNengValue))
    {
        ClosePositions(POSITION_TYPE_SELL);
    }
}

//+------------------------------------------------------------------+
//| 亚洲时段特殊算法 - GBPCAD专用                                     |
//+------------------------------------------------------------------+
bool CChaoNengStrategy::ChaoNeng_LongEntry_Asian(double closePrice, double adaptiveLow, double chaoNengVal, double speedLow)
{
    // 亚洲时段多单开仓 - 正向逻辑：特殊参数（波动率-1000更宽松）
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_longPositions < 1 &&                                                          // 多单数量少于1
       (double)(m_pipsFactor * (-1000)) * m_pointSize < closePrice - adaptiveLow &&   // 特殊波动率参数（更宽松）
       (double)(openFactor - 100) >= chaoNengVal &&                                   // 超能指标条件满足
       speedLow > closePrice &&                                                       // 速度指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足亚洲时段多单开仓条件
    }
    return false;     // 不满足亚洲时段多单开仓条件
}

bool CChaoNengStrategy::ChaoNeng_ShortEntry_Asian(double adaptiveHigh, double closePrice, double chaoNengVal, double speedHigh)
{
    // 亚洲时段空单开仓 - 正向逻辑：特殊参数（波动率-1000更宽松）
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_shortPositions < 1 &&                                                         // 空单数量少于1
       (double)(m_pipsFactor * (-1000)) * m_pointSize < adaptiveHigh - closePrice &&  // 特殊波动率参数（更宽松）
       (double)-openFactor <= chaoNengVal &&                                          // 超能指标条件满足
       speedHigh < closePrice &&                                                      // 速度指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足亚洲时段空单开仓条件
    }
    return false;     // 不满足亚洲时段空单开仓条件
}

bool CChaoNengStrategy::ChaoNeng_SpecialLongEntry_Asian(double currentPrice, double adaptiveHigh, double adaptiveLow)
{
    // 亚洲时段特殊多单开仓 - 正向逻辑：特殊参数（技术条件1000）
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_longPositions < 5 &&                                                          // 多单数量少于5
       m_longOpenPrice > 0.0 &&                                                       // 已有多单开仓价
       (double)(3 * m_pipsFactor) * m_pointSize < m_longOpenPrice - currentPrice &&   // 价格距离条件满足
       0.5 * ((adaptiveHigh + adaptiveLow) * 0.5 + adaptiveLow) < 1000 &&             // 特殊技术条件参数
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足亚洲时段特殊多单开仓条件
    }
    return false;     // 不满足亚洲时段特殊多单开仓条件
}

bool CChaoNengStrategy::ChaoNeng_SpecialShortEntry_Asian(double currentPrice, double adaptiveHigh, double adaptiveLow)
{
    // 亚洲时段特殊空单开仓 - 正向逻辑：特殊参数（技术条件-1000）
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_shortPositions < 5 &&                                                         // 空单数量少于5
       m_shortOpenPrice > 0.0 &&                                                      // 已有空单开仓价
       (double)(3 * m_pipsFactor) * m_pointSize < currentPrice - m_shortOpenPrice &&  // 价格距离条件满足
       0.5 * ((adaptiveHigh + adaptiveLow) * 0.5 + adaptiveHigh) > -1000 &&           // 特殊技术条件参数
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足亚洲时段特殊空单开仓条件
    }
    return false;     // 不满足亚洲时段特殊空单开仓条件
}

//+------------------------------------------------------------------+
//| ChaoNeng 算法 - 重构优化版本（保持核心逻辑不变）                  |
//+------------------------------------------------------------------+

// 超能指标计算 - 核心算法不变
double CChaoNengStrategy::CalculateChaoNengIndicator(double high, double close, double highest, double lowest)
{
    return (high - close) * (-100.0) / (highest - lowest);
}

// 普通多单开仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_LongEntry(double closePrice, double adaptiveLow, double chaoNengVal, double speedLow)
{
    // 正向逻辑：当所有条件都满足时可以开多单
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_longPositions < 1 &&                                                          // 多单数量少于1
       (double)(m_pipsFactor * volatilityPeriod) * m_pointSize < closePrice - adaptiveLow &&  // 波动率条件满足
       (double)(openFactor - 100) >= chaoNengVal &&                                   // 超能指标条件满足
       speedLow > closePrice &&                                                       // 速度指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        Print("【多单信号触发】价格:", closePrice, " 自适应低:", adaptiveLow, " 超能值:", chaoNengVal, " 速度低:", speedLow);
        return true;  // 满足开多单条件
    }
    return false;     // 不满足开多单条件
}

// 普通空单开仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_ShortEntry(double adaptiveHigh, double closePrice, double chaoNengVal, double speedHigh)
{
    // 正向逻辑：当所有条件都满足时可以开空单
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_shortPositions < 1 &&                                                         // 空单数量少于1
       (double)(m_pipsFactor * volatilityPeriod) * m_pointSize < adaptiveHigh - closePrice &&  // 波动率条件满足
       (double)-openFactor <= chaoNengVal &&                                          // 超能指标条件满足
       speedHigh < closePrice &&                                                      // 速度指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        Print("【空单信号触发】自适应高:", adaptiveHigh, " 价格:", closePrice, " 超能值:", chaoNengVal, " 速度高:", speedHigh);
        return true;  // 满足开空单条件
    }
    return false;     // 不满足开空单条件
}

// 特殊多单开仓条件 - 正向逻辑：限制持仓数量5个以内
bool CChaoNengStrategy::ChaoNeng_SpecialLongEntry(double currentPrice, double adaptiveHigh, double adaptiveLow)
{
    // 正向逻辑：当所有条件都满足时可以开特殊多单
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_longPositions < 5 &&                                                          // 多单数量少于5
       m_longOpenPrice > 0.0 &&                                                       // 已有多单开仓价
       (double)(3 * m_pipsFactor) * m_pointSize < m_longOpenPrice - currentPrice &&   // 价格距离条件满足
       0.5 * ((adaptiveHigh + adaptiveLow) * 0.5 + adaptiveLow) < iClose(_Symbol, _Period, 1) &&  // 技术条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足特殊开多单条件
    }
    return false;     // 不满足特殊开多单条件
}

// 特殊空单开仓条件 - 正向逻辑：限制持仓数量5个以内
bool CChaoNengStrategy::ChaoNeng_SpecialShortEntry(double currentPrice, double adaptiveHigh, double adaptiveLow)
{
    // 正向逻辑：当所有条件都满足时可以开特殊空单
    if(m_spreadOK == 1 &&                                                              // 点差正常
       m_shortPositions < 5 &&                                                         // 空单数量少于5
       m_shortOpenPrice > 0.0 &&                                                      // 已有空单开仓价
       (double)(3 * m_pipsFactor) * m_pointSize < currentPrice - m_shortOpenPrice &&  // 价格距离条件满足
       0.5 * ((adaptiveHigh + adaptiveLow) * 0.5 + adaptiveHigh) > iClose(_Symbol, _Period, 1) &&  // 技术条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足特殊开空单条件
    }
    return false;     // 不满足特殊开空单条件
}

// 多单突破平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_LongBreakoutClose(double closePrice, double speedHigh, double chaoNengVal)
{
    // 正向逻辑：当所有条件都满足时可以平掉多单
    if(m_longPositions > 0 &&                                                          // 有多单持仓
       speedHigh < closePrice &&                                                       // 突破速度高点
       (double)-closeFactor <= chaoNengVal &&                                         // 超能指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        Print("【多单突破平仓信号】价格突破速度高点 当前价:", closePrice, " 速度高:", speedHigh, " 超能值:", chaoNengVal);
        return true;  // 满足多单突破平仓条件
    }
    return false;     // 不满足多单突破平仓条件
}

// 空单突破平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_ShortBreakoutClose(double closePrice, double speedLow, double chaoNengVal)
{
    // 正向逻辑：当所有条件都满足时可以平掉空单
    if(m_shortPositions > 0 &&                                                         // 有空单持仓
       speedLow > closePrice &&                                                        // 突破速度低点
       (double)(closeFactor - 100) >= chaoNengVal &&                                  // 超能指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        Print("【空单突破平仓信号】价格突破速度低点 当前价:", closePrice, " 速度低:", speedLow, " 超能值:", chaoNengVal);
        return true;  // 满足空单突破平仓条件
    }
    return false;     // 不满足空单突破平仓条件
}    

// 多单盈利平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_LongProfitClose(double closePrice)
{
    // 正向逻辑：当所有条件都满足时可以平掉多单获利
    if(m_longPositions > 0 &&                                                          // 有多单持仓
       (double)(m_pipsFactor * profitFactor) * m_pointSize + m_longOpenPrice < closePrice &&  // 达到盈利目标
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        double profitPoints = (closePrice - m_longOpenPrice) / m_pointSize;
        Print("【多单盈利平仓信号】开仓价:", m_longOpenPrice, " 当前价:", closePrice, " 盈利点数:", DoubleToString(profitPoints, 1));
        return true;  // 满足多单盈利平仓条件
    }
    return false;     // 不满足多单盈利平仓条件
}

// 空单盈利平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_ShortProfitClose(double closePrice)
{
    // 正向逻辑：当所有条件都满足时可以平掉空单获利
    if(m_shortPositions > 0 &&                                                         // 有空单持仓
       m_shortOpenPrice - (double)(m_pipsFactor * profitFactor) * m_pointSize > closePrice &&  // 达到盈利目标
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        double profitPoints = (m_shortOpenPrice - closePrice) / m_pointSize;
        Print("【空单盈利平仓信号】开仓价:", m_shortOpenPrice, " 当前价:", closePrice, " 盈利点数:", DoubleToString(profitPoints, 1));
        return true;  // 满足空单盈利平仓条件
    }
    return false;     // 不满足空单盈利平仓条件
}

// 多单盈亏平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_LongPnLClose(double chaoNengVal)
{
    // 正向逻辑：当所有条件都满足时可以平掉多单（基于盈亏）
    if(m_longPositions > 0 &&                                                          // 有多单持仓
       m_longProfit > 0.0 &&                                                          // 有盈利
       (double)-closeFactor2 <= chaoNengVal &&                                        // 超能指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足多单盈亏平仓条件
    }
    return false;     // 不满足多单盈亏平仓条件
}

// 空单盈亏平仓条件 - 正向逻辑：满足条件时返回true
bool CChaoNengStrategy::ChaoNeng_ShortPnLClose(double chaoNengVal)
{
    // 正向逻辑：当所有条件都满足时可以平掉空单（基于盈亏）
    if(m_shortPositions > 0 &&                                                         // 有空单持仓
       m_shortProfit > 0.0 &&                                                         // 有盈利
       (double)(closeFactor2 - 100) >= chaoNengVal &&                                 // 超能指标条件满足
       (double)TimeCurrent() <= (double)EXPIRY_DATE)                                  // 未过期
    {
        return true;  // 满足空单盈亏平仓条件
    }
    return false;     // 不满足空单盈亏平仓条件
}

//+------------------------------------------------------------------+
//| 交易执行函数 - 重构优化版本                                       |
//+------------------------------------------------------------------+

// 执行多单开仓 - 优化版本，保持核心逻辑不变
void CChaoNengStrategy::ExecuteLongEntry()
{
    double stopLoss = 0, takeProfit = 0;
    double lotSize = CalculateLotSize();
    
    // 计算止损价格
    if(enableAsianSession == true)
    {
        stopLoss = NormalizeDouble(m_askPrice - stopLossPoints * m_pipsFactor * m_pointSize, _Digits);
    }
    else
    {
        stopLoss = NormalizeDouble(m_adaptiveLow, _Digits);
    }
    
    // 计算止盈价格
    takeProfit = NormalizeDouble(m_adaptiveHigh - m_adaptiveLow + (m_adaptiveHigh + m_adaptiveLow) / 2, _Digits);
    
    // 执行开仓
    if(m_trade.Buy(lotSize, _Symbol, 0, stopLoss, takeProfit, eaComment))
    {
        Print("【开多单成功】品种:", _Symbol, " 手数:", lotSize, " 价格:", SymbolInfoDouble(_Symbol, SYMBOL_ASK), " 止损:", stopLoss, " 止盈:", takeProfit);
    }
    else
    {
        Print("【开多单失败】品种:", _Symbol, " 手数:", lotSize, " 错误代码:", _LastError);
    }
}

// 执行空单开仓 - 优化版本，保持核心逻辑不变
void CChaoNengStrategy::ExecuteShortEntry()
{
    double stopLoss = 0, takeProfit = 0;
    double lotSize = CalculateLotSize();
    
    // 计算止损价格
    if(enableAsianSession == true)
    {
        stopLoss = NormalizeDouble(stopLossPoints * m_pipsFactor * m_pointSize + m_bidPrice, _Digits);
    }
    else
    {
        stopLoss = NormalizeDouble(m_adaptiveHigh, _Digits);
    }
    
    // 计算止盈价格
    takeProfit = NormalizeDouble((m_adaptiveHigh + m_adaptiveLow) / 2 - (m_adaptiveHigh - m_adaptiveLow), _Digits);
    
    // 执行开仓
    if(m_trade.Sell(lotSize, _Symbol, 0, stopLoss, takeProfit, eaComment))
    {
        Print("【开空单成功】品种:", _Symbol, " 手数:", lotSize, " 价格:", SymbolInfoDouble(_Symbol, SYMBOL_BID), " 止损:", stopLoss, " 止盈:", takeProfit);
    }
    else
    {
        Print("【开空单失败】品种:", _Symbol, " 手数:", lotSize, " 错误代码:", _LastError);
    }
}

//+------------------------------------------------------------------+
//| 更新持仓统计信息                                                 |
//+------------------------------------------------------------------+
void CChaoNengStrategy::UpdatePositionStatistics()
{
    // 重置统计数据
    m_longPositions = 0;
    m_shortPositions = 0;
    m_longLots = 0.0;
    m_shortLots = 0.0;
    m_longProfit = 0.0;
    m_shortProfit = 0.0;
    m_longOpenPrice = 0.0;
    m_shortOpenPrice = 0.0;
    m_longOpenTime = 0;
    m_shortOpenTime = 0;
    
    // 遍历所有持仓
    for(int i = 0; i < PositionsTotal(); i++)
    {
        if(m_position.SelectByIndex(i) && 
           m_position.Symbol() == _Symbol && 
           m_position.Magic() == MAGIC_NUMBER)
        {
            if(m_position.PositionType() == POSITION_TYPE_BUY)
            {
                m_longPositions++;
                m_longLots += m_position.Volume();
                m_longProfit += m_position.Profit() + m_position.Commission() + m_position.Swap();
                m_longOpenPrice = m_position.PriceOpen();  // 最后一单的开仓价
                m_longOpenTime = m_position.Time();
            }
            else if(m_position.PositionType() == POSITION_TYPE_SELL)
            {
                m_shortPositions++;
                m_shortLots += m_position.Volume();
                m_shortProfit += m_position.Profit() + m_position.Commission() + m_position.Swap();
                m_shortOpenPrice = m_position.PriceOpen();  // 最后一单的开仓价
                m_shortOpenTime = m_position.Time();
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 平仓指定类型的所有持仓                                           |
//+------------------------------------------------------------------+
void CChaoNengStrategy::ClosePositions(ENUM_POSITION_TYPE posType)
{
    string typeStr = (posType == POSITION_TYPE_BUY) ? "多单" : "空单";
    int closedCount = 0;
    
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(m_position.SelectByIndex(i) && 
           m_position.Symbol() == _Symbol && 
           m_position.Magic() == MAGIC_NUMBER && 
           m_position.PositionType() == posType)
        {
            double profit = m_position.Profit() + m_position.Commission() + m_position.Swap();
            double volume = m_position.Volume();
            
            if(m_trade.PositionClose(m_position.Ticket()))
            {
                Print("【平仓成功】", typeStr, " 手数:", volume, " 盈亏:", DoubleToString(profit, 2), " 品种:", _Symbol);
                closedCount++;
            }
            else
            {
                Print("【平仓失败】", typeStr, " 错误:", _LastError);
            }
        }
    }
    
    if(closedCount > 0)
    {
        Print("【平仓总结】共平仓", closedCount, "个", typeStr, " 品种:", _Symbol);
    }
}

//+------------------------------------------------------------------+
//| 计算手数 - 保持原有逻辑                                          |
//+------------------------------------------------------------------+
double CChaoNengStrategy::CalculateLotSize()
{
    double lotSize = 0.0;
    
    // 基础手数计算
    if(enableCompounding == true)
    {
        // BTC价格较高，需要调整复利计算除数
        if(StringFind(_Symbol, "BTC", 0) >= 0 || StringFind(_Symbol, "BITCOIN", 0) >= 0)
        {
            lotSize = StringToDouble(DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY) * riskPercent / 100000, 3));  // BTC使用10万作为除数
            Print("【BTC复利计算】权益:", AccountInfoDouble(ACCOUNT_EQUITY), " 风险%:", riskPercent, " 除数:100000 计算手数:", lotSize);
        }
        else
        {
            lotSize = StringToDouble(DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY) * riskPercent / 1000000, 2));
            Print("【复利计算】权益:", AccountInfoDouble(ACCOUNT_EQUITY), " 风险%:", riskPercent, " 除数:1000000 计算手数:", lotSize);
        }
    }
    else
    {
        lotSize = baseLotSize;
    }
    
    // 动态调整手数 - 保持原有逻辑
    if(m_askPrice - m_adaptiveLow > m_pipsFactor * 110 * m_pointSize && 
       enableDynamicLots == true && 
       enableAsianSession != true)
    {
        double oldLotSize = lotSize;
        lotSize = lotSize * 1.6;
        Print("【动态手数】触发条件: 价差=", DoubleToString(m_askPrice - m_adaptiveLow, 5), " 阈值=", DoubleToString(m_pipsFactor * 110 * m_pointSize, 5), " 手数:", oldLotSize, "->", lotSize);
    }
    
    // 手数限制 - 针对不同品种设置不同限制
    if(StringFind(_Symbol, "BTC", 0) >= 0 || StringFind(_Symbol, "BITCOIN", 0) >= 0)
    {
        double originalLot = lotSize;
        // BTC手数限制：1手=1个BTC，通常最大5-10手
        if(lotSize > 5) lotSize = 5;    // BTC最大5手
        if(lotSize < 0.01) lotSize = 0.01;  // BTC最小0.01手
        Print("【BTC手数限制】原始:", originalLot, " 最终:", lotSize, " 当前价格:", SymbolInfoDouble(_Symbol, SYMBOL_ASK), " 账户权益:", AccountInfoDouble(ACCOUNT_EQUITY));
    }
    else
    {
        double originalLot = lotSize;
        // 黄金等其他品种的手数限制
        if(lotSize > 50) lotSize = 50;
        if(lotSize < 0.01) lotSize = 0.01;
        if(originalLot != lotSize)
        {
            Print("【手数限制】品种:", _Symbol, " 原始:", originalLot, " 最终:", lotSize);
        }
    }
    
    return lotSize;
}

//+------------------------------------------------------------------+
//| 辅助方法实现                                                     |
//+------------------------------------------------------------------+

// 获取指定周期的最高价
double CChaoNengStrategy::GetHighestPrice(int period, int shift)
{
    int highestBar = iHighest(_Symbol, _Period, MODE_HIGH, period, shift);
    return iHigh(_Symbol, _Period, highestBar);
}

// 获取指定周期的最低价
double CChaoNengStrategy::GetLowestPrice(int period, int shift)
{
    int lowestBar = iLowest(_Symbol, _Period, MODE_LOW, period, shift);
    return iLow(_Symbol, _Period, lowestBar);
}

// 设置时间间隔
void CChaoNengStrategy::SetTimeInterval()
{
    datetime currentTime = iTime(_Symbol, _Period, 1);
    datetime previousTime = iTime(_Symbol, _Period, 2);
    m_barTimeInterval = currentTime - previousTime;
}

// 判断是否为亚洲交易时段
bool CChaoNengStrategy::IsAsianSession()
{
    MqlDateTime time_struct;
    
    if(MQLInfoInteger(MQL_TESTER))
    {
        // 回测环境下的时间判断
        TimeToStruct(TimeCurrent(), time_struct);
        return (time_struct.hour <= asianStartHour || time_struct.hour >= asianEndHour);
    }
    else
    {
        // 实盘环境下的时间判断（本地时间）
        TimeToStruct(TimeLocal(), time_struct);
        return (time_struct.hour >= 3 && time_struct.hour <= 9);  // 亚洲时段 3:00-9:00
    }
}

// 创建标签
void CChaoNengStrategy::CreateLabel(string name, string text, int corner, int x, int y, int size, color clr)
{
    ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
    ObjectSetString(0, name, OBJPROP_TEXT, text);
    ObjectSetInteger(0, name, OBJPROP_FONTSIZE, size);
    ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
    ObjectSetInteger(0, name, OBJPROP_CORNER, corner);
    ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
}

// 创建UI元素
void CChaoNengStrategy::CreateUIElements()
{
    // 创建控制按钮
    ObjectCreate(0, "EURUSD", OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, "EURUSD", OBJPROP_XDISTANCE, 330);
    ObjectSetInteger(0, "EURUSD", OBJPROP_YDISTANCE, 245);
    ObjectSetInteger(0, "EURUSD", OBJPROP_XSIZE, 15);
    ObjectSetInteger(0, "EURUSD", OBJPROP_YSIZE, 15);
    ObjectSetInteger(0, "EURUSD", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetString(0, "EURUSD", OBJPROP_TEXT, "");
    ObjectSetString(0, "EURUSD", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "EURUSD", OBJPROP_FONTSIZE, 9);
    ObjectSetInteger(0, "EURUSD", OBJPROP_COLOR, clrLightSlateGray);
    ObjectSetInteger(0, "EURUSD", OBJPROP_BGCOLOR, clrLightSlateGray);
    ObjectSetInteger(0, "EURUSD", OBJPROP_BORDER_COLOR, clrDimGray);
    ObjectSetInteger(0, "EURUSD", OBJPROP_BACK, false);
    ObjectSetInteger(0, "EURUSD", OBJPROP_STATE, false);
    ObjectSetInteger(0, "EURUSD", OBJPROP_SELECTABLE, false);
    ObjectSetInteger(0, "EURUSD", OBJPROP_SELECTED, false);
    ObjectSetInteger(0, "EURUSD", OBJPROP_HIDDEN, false);
}

// 更新显示界面 - 优化版本，保持原有显示逻辑
void CChaoNengStrategy::UpdateDisplay()
{
    CreateLabel("sd2", "EA运行状态：", CORNER_RIGHT_LOWER, 10, 60, 9, clrMagenta);
    
    if(m_tradingAllowed == false)
    {
        CreateLabel("sd3", "↓ ---运行失败，有以下原因--- ↓", CORNER_RIGHT_UPPER, 105, 60, 9, clrYellow);
        // 清除持仓信息显示
        ObjectDelete(0, "多亏1"); ObjectDelete(0, "多数1"); ObjectDelete(0, "多量1"); ObjectDelete(0, "分界1");
        ObjectDelete(0, "空亏1"); ObjectDelete(0, "空数1"); ObjectDelete(0, "空量1");
        ObjectDelete(0, "多亏2"); ObjectDelete(0, "多数2"); ObjectDelete(0, "多量2");
        ObjectDelete(0, "空亏2"); ObjectDelete(0, "空数2"); ObjectDelete(0, "空量2");
    }
    else
    {
        CreateLabel("sd3", "-----运行正常-----", CORNER_RIGHT_UPPER, 105, 60, 10, clrLime);
        
        // 多单信息显示标签
        CreateLabel("多亏1", "多单盈亏 : ", CORNER_RIGHT_LOWER, 105, 80, 9, clrDodgerBlue);
        CreateLabel("多数1", "多单手数 : ", CORNER_RIGHT_LOWER, 105, 100, 9, clrDodgerBlue);
        CreateLabel("多量1", "多单数量 : ", CORNER_RIGHT_LOWER, 105, 120, 9, clrDodgerBlue);
        CreateLabel("分界1", "------------------------", CORNER_RIGHT_LOWER, 105, 140, 9, clrOrangeRed);
        
        // 空单信息显示标签
        CreateLabel("空亏1", "空单盈亏 : ", CORNER_RIGHT_LOWER, 105, 160, 9, clrOrangeRed);
        CreateLabel("空数1", "空单手数 : ", CORNER_RIGHT_LOWER, 105, 180, 9, clrOrangeRed);
        CreateLabel("空量1", "空单数量 : ", CORNER_RIGHT_LOWER, 105, 200, 9, clrOrangeRed);
        
        // 数值显示 - 使用优化后的成员变量
        CreateLabel("多亏2", DoubleToString(m_longProfit, 2), CORNER_RIGHT_LOWER, 175, 80, 9, clrDodgerBlue);
        CreateLabel("多数2", DoubleToString(m_longLots, 2), CORNER_RIGHT_LOWER, 175, 100, 9, clrDodgerBlue);
        CreateLabel("多量2", DoubleToString(m_longPositions, 0), CORNER_RIGHT_LOWER, 175, 120, 9, clrDodgerBlue);
        CreateLabel("空亏2", DoubleToString(m_shortProfit, 2), CORNER_RIGHT_LOWER, 175, 160, 9, clrOrangeRed);
        CreateLabel("空数2", DoubleToString(m_shortLots, 2), CORNER_RIGHT_LOWER, 175, 180, 9, clrOrangeRed);
        CreateLabel("空量2", DoubleToString(m_shortPositions, 0), CORNER_RIGHT_LOWER, 175, 200, 9, clrOrangeRed);
    }
}

//+------------------------------------------------------------------+
//| 图表事件处理                                                     |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
    g_strategy.OnChartEvent(id, lparam, dparam, sparam);
}

void CChaoNengStrategy::OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
    if(id == CHARTEVENT_OBJECT_CLICK)
    {
        if(sparam == "EURUSD")
        {
            ObjectSetInteger(0, "EURUSD", OBJPROP_STATE, false);
            // 可以在这里添加按钮点击的处理逻辑
            Print("控制按钮被点击");
        }
    }
}

//+------------------------------------------------------------------+
//| 重构总结                                                         |
//+------------------------------------------------------------------+
/*
重构优化完成！主要改进：

1. 【面向对象设计】
   - 创建 CChaoNengStrategy 类封装所有逻辑
   - 消除全局变量，使用有意义的成员变量名
   - 清晰的职责分离和模块化设计

2. 【性能优化】  
   - 技术指标缓存机制：只在新K线时计算，避免每个tick重复计算
   - 减少重复的函数调用和数据获取

3. 【代码可读性】
   - 重命名所有变量为有意义的英文名称
   - 添加详细的方法注释和逻辑说明
   - 清晰的方法分组和命名约定

4. 【参数管理】
   - 使用类成员变量替代大量函数参数传递
   - 统一的参数验证和边界检查

5. 【核心逻辑保持不变】
   - 所有 ChaoNeng 算法的数学逻辑完全保持原样
   - 开仓平仓条件判断逻辑不变
   - 手数计算和风险控制逻辑保持一致
   - 亚洲时段特殊策略逻辑保持原样

6. 【错误处理】
   - 改进的错误信息输出
   - 更好的异常情况处理

核心交易逻辑完全保持原有的 MT4 版本逻辑，只是在代码结构和可维护性上做了大幅优化！
*/ 